public class NumTrees {

    public int numTrees1(int n) {
        int[][] dp = new int[n + 1][n + 1];
        process(1, n, dp);
        return dp[1][n];
    }

    public int process(int start, int end, int[][] dp) {
        if (start < 0 || start > dp.length - 1 || end < 0 || end > dp.length - 1) return 1;
        if (dp[start][end] != 0) return dp[start][end];
        if (start >= end) {
            dp[start][end] = 1;
        } else {
            int ans = 0;
            for (int i = start; i <= end; i++) {
                ans += process(start, i - 1, dp) * process(i + 1, end, dp);
            }
            dp[start][end] = ans;
        }
        return dp[start][end];
    }

    public int numTrees(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }
}
